package com.blaze.framework.starter.test;

import org.jeasy.random.EasyRandom;
import org.jeasy.random.EasyRandomParameters;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalTime;

/**
 * Easy Random 提供的自动生成对象的方法.
 * {@link org.junit.jupiter.api.extension.ExtendWith} 添加该拓展点, 用于随机生成对象.
 * <pre class="code">
 *     public class Test {
 *          &#064;Test
 *          public void testRandomParameterExtension(EasyRandom easyRandom) {
 *              // 由于参数中有EasyRandom, 该扩展点会进行解析
 *          }
 *     }
 * </pre>
 * @author create by Zhou Zongbo on 2021/12/14.
 */
public class RandomParameterExtension implements ParameterResolver {
    
    @Override
    public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
            throws ParameterResolutionException {
        return parameterContext.getParameter().getType().equals(EasyRandom.class);
    }
    
    @Override
    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
            throws ParameterResolutionException {
        return new EasyRandom(randomParameters());
    }
    
    private EasyRandomParameters randomParameters() {
        return new EasyRandomParameters()
                .seed(123L)
                .objectPoolSize(100)
                .randomizationDepth(3)
                .charset(StandardCharsets.UTF_8)
                .timeRange(LocalTime.of(9, 0), LocalTime.of(20, 0))
                .dateRange(LocalDate.now(), LocalDate.now().plusDays(7))
                .stringLengthRange(5, 50)
                .collectionSizeRange(1, 10)
                .scanClasspathForConcreteTypes(true)
                .overrideDefaultInitialization(false)
                .ignoreRandomizationErrors(true);
    }
}
